package com.whty.cms.filewps.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created by Administrator on 2019/3/21 0021.
 */
public class SignatureUtils {
    private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";

    /**
     *
     * @param data
     * @param key
     * @return
     */
    public static String genHMAC(String data, String key) {
        byte[] result = null;
        try {
            //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
            SecretKeySpec signinKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
            //生成一个指定 Mac 算法 的 Mac 对象
            Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
            //用给定密钥初始化 Mac 对象
            mac.init(signinKey);
            //完成 Mac 操作
            byte[] rawHmac = mac.doFinal(data.getBytes());
            result = Base64.encodeBase64(rawHmac);

        } catch (NoSuchAlgorithmException e) {
            System.err.println(e.getMessage());
        } catch (InvalidKeyException e) {
            System.err.println(e.getMessage());
        }
        if (null != result) {
            return new String(result);
        } else {
            return null;
        }
    }

    public static String getWpsSignature(TreeMap<String, String> map) {
        String secretId = "95a00a14a1184ac17cee5d678514c70e";
        String secretKey = "51e9b9e1a1b242ab778c1be8eb20e641";
        StringBuffer sb = new StringBuffer(secretId);
        for(Map.Entry<String, String> mapping:map.entrySet()){
            sb.append(mapping.getKey());
            sb.append(mapping.getValue());
            System.out.println(mapping.getKey()+":"+mapping.getValue());
        }
        sb.append(secretKey);
        return genHMAC(sb.toString(), secretKey);
    }
}
